﻿using NPOI.SS.Formula.Functions;
using System.Collections.Generic;
using System.Linq;

namespace CoreLims.Models.CoreLims
{
    public static class MaterialExtension
    {
        public static Material getMaterial(this Material material, CoreLimsContext dbContext, string Code) =>
            dbContext.Material.Where(s => s.Code == Code).FirstOrDefault();

        public static List<Material> getMaterialList(this Material material, CoreLimsContext dbContext) =>
            dbContext.Material.ToList();

        /// <summary>
        /// 根据设备类型和ID，获得与设备有关的备件信息
        /// </summary>
        /// <param name="material"></param>
        /// <param name="dbContext"></param>
        /// <param name="EquipmentType"></param>
        /// <param name="EquipmentId"></param>
        /// <returns></returns>
        public static List<Material> getMateriasByEqTypeId(this Material material, CoreLimsContext dbContext, string EquipmentType, string EquipmentId) =>
            dbContext.Material.Where(s => s.EquipmentType == EquipmentType || s.EquipmentId == EquipmentId).ToList();

        public static string UpdateMaterialEnable(this Material material, CoreLimsContext dbContext, string Id, string isEnable)
        {
            var material1 = INV.Material.getMaterial(dbContext, Id);

            if (isEnable == "true")
                material1.IsEnable = true;
            else
                material1.IsEnable = false;

            dbContext.Update(material1);
            dbContext.SaveChanges();
            return "启用/停用 更新成功！";
        }

        public static string UpdateMaterialIsReview(this Material material, CoreLimsContext dbContext, string Id, string IsReview)
        {
            var material1 = INV.Material.getMaterial(dbContext, Id);

            if (IsReview == "true")
                material1.IsReview = true;
            else
                material1.IsReview = false;

            dbContext.Update(material1);
            dbContext.SaveChanges();
            return "管控状态更新成功！";
        }

        /// <summary>
        /// 删除物料与设备的关联
        /// </summary>
        /// <param name="material"></param>
        /// <param name="dbContext"></param>
        /// <param name="Code"></param>
        /// <returns></returns>
        public static string DelRelatedMaterialAndEq(this Material material, CoreLimsContext dbContext, string Code)
        {
            var material1 = INV.Material.getMaterial(dbContext, Code);
            if (material1.EquipmentId != null)
                material1.EquipmentId = null;

            if (material1.EquipmentType != null)
                material1.EquipmentType = null;
            
            dbContext.Update(material1);
            dbContext.SaveChanges();
            return "物料与设备关联删除成功！";
        }

    }

}
